package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Rideo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;

/**
 * @author SunSun
 * @date 2021/11/7
 */
@DubboService
public class RideoApiImpl implements RideoApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;
    @Override
    public String upload(Rideo rideo) {
        rideo.setRid(idWorker.getNextId("rideo"));
        mongoTemplate.save(rideo);
        return rideo.getId().toHexString();
    }

    @Override
    public Rideo randomRideo() {
        TypedAggregation<Rideo> movementTypedAggregation = Aggregation.newAggregation(Rideo.class, Aggregation.sample(1));
        AggregationResults<Rideo> aggregate = mongoTemplate.aggregate(movementTypedAggregation, Rideo.class);
        return aggregate.getUniqueMappedResult();
    }
}
